#pragma once
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>

#include "log.hpp"

enum
{
    SOCKET_ERR = 1,
    CONNCET_ERR,
    LISTEN_ERR,
    ACCETP_ERR,
    USAGE_ERR
};

class TcpClient
{
public:
    TcpClient(const std::string &ip, const uint16_t port)
    : _port(port), _ip(ip), _sockfd(-1)
    {}

    void initClient()
    {
        //创建客户端的socket套接字
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            logMessage(FATAL, "create socket error");
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL, "create socket success");

        //客户端不需要显示的bind，操作系统自动完成
        //创建完套接字后，客户端只需要发起连接
    }

    void start()
    {
        while (true)
        {
            //向谁发起连接
            struct sockaddr_in peer;
            peer.sin_family = AF_INET;
            peer.sin_port = htons(_port);
            peer.sin_addr.s_addr = inet_addr(_ip.c_str());

            if (connect(_sockfd, (struct sockaddr *)&peer, sizeof(peer)) != 0)
            {
                logMessage(FATAL, "connect error");
                exit(CONNCET_ERR);
            }
            else
            {
                std::string message;
                while (true)
                {
                    std::cout << "Enter# ";
                    std::getline(std::cin, message);
                    write(_sockfd, message.c_str(), message.size());

                    char buffer[1024];
                    int n = read(_sockfd, buffer, sizeof(buffer)- 1);
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        std::cout << "Server#" << buffer << std::endl;
                    }
                    else break;
                }
            }
        }
    }

    ~TcpClient()
    {}

private:
    uint16_t _port;
    std::string _ip;
    int _sockfd;
};